package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.entity.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：sean
 * @date ：Created in 2022/5/19
 * @description ：
 * @version: 1.0
 */
@Service
public class SetmealServiceImpl
	extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

	@Autowired
	private SetmealDishService setmealDishService;

	@Transactional
	@Override
	public void saveWithDish(SetmealDto setmealDto) {
		// 扩展方法
		// 保存套餐基本信息,一个套餐包含多个菜品
		this.save(setmealDto);
		// 保存套餐菜品关系列表，批量保存
		List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
		List<SetmealDish> setmealDishList = setmealDishes.stream().map((item) -> {
			item.setSetmealId(setmealDto.getId());
			return item;
		}).collect(Collectors.toList());
		setmealDishService.saveBatch(setmealDishList);
	}

	@Transactional
	@Override
	public void removeWithDish(List<Long> ids) {
		// 扩展业务类
		// 删除套餐列表 （套餐表） Setmeal表
		// 查询删除的套餐是否是在售状态
		LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
		// select count(*) from setmeal where id in (12,23,8)
		//setmealLambdaQueryWrapper.in(Setmeal::getId,ids);
		// 1正在使用，不能删除
		setmealLambdaQueryWrapper.eq(Setmeal::getStatus,1);
		// 基于条件查询
		int count = this.count(setmealLambdaQueryWrapper);
		if(count > 0){
			throw new CustomException("套餐正在售卖，不能删除");
		}
		// 批量删除套餐，基于Id删除
		this.removeByIds(ids);
		// 删除套餐菜品关系表 (关系表) SetmealDish表
		LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
		setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
		// 基于条件删除
		setmealDishService.remove(setmealDishLambdaQueryWrapper);
	}
}
